package com.example.service.user.impl;

import java.util.HashMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.example.common.StatusText;
import com.example.dao.user.UserDao;
import com.example.entity.vo.user.UserRegisterVo;
import com.example.security.JwtTokenUtil;
import com.example.service.user.UserService;
import com.example.service.user.impl.UserServiceImpl;

@Service
public class UserServiceImpl implements UserService{

	@Autowired
	private AuthenticationManager authenticationManager;
	@Autowired
	private UserDetailsService userDetailsService;
	@Autowired
	private JwtTokenUtil jwtTokenUtil;
	@Autowired
	private UserDao userDao;

	@Value("${security.jwt.tokenHead}")
	private String tokenHead;

	@Override
	public HashMap<String, Object> login(String username, String password) {
		try {
			UsernamePasswordAuthenticationToken upToken = new UsernamePasswordAuthenticationToken(username, password);
			Authentication authentication = authenticationManager.authenticate(upToken);
			SecurityContextHolder.getContext().setAuthentication(authentication);
			UserDetails userDetails = userDetailsService.loadUserByUsername(username);
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("token", jwtTokenUtil.generateToken(userDetails));
			map.put("user", userDao.getUser(username));
			return map;
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public Integer register(UserRegisterVo user) {
		String username = user.getUsername();
		if (userDao.findByUsername(username) != null) {
			return StatusText.USER_REGISTER_EXIST;
		}
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		String rawPassword = user.getPassword();
		user.setPassword(encoder.encode(rawPassword));
		if (userDao.addUser(user) > 0) {
			return StatusText.USER_REGISTER_SUCCESS;
		} else {
			return StatusText.USER_REGISTER_FAIL;
		}
	}

	@Override
	public String refreshToken(String oldToken) {
		String token = oldToken.substring(tokenHead.length());
		if (!jwtTokenUtil.isTokenExpired(token)) {
			return jwtTokenUtil.refreshToken(token);
		}
		return "error";
	}

}
